package com.tfy.liquor.config;

import com.alibaba.fastjson.JSON;
import com.tfy.liquor.bean.Result;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 拦截器
 */
public class Interceptors implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        StringBuffer requestURL = request.getRequestURL();
        System.err.println("前置拦截器1 preHandle： 请求的uri为：" + requestURL.toString());
        //登录放行
//        if ("/login".equals(request.getRequestURI())) {
//            return true;}
//        静态资源放行
        if ((requestURL.toString()).contains("static")) {
            System.err.println("静态资源放行");
            return true;}
        // 获取token
        String token = request.getHeader("token");
        if (null == token) {
            // 返回数据
            String result = JSON.toJSONString(new Result().no_Login());
            returnJson(response, result);
            return false;
        }

        return true;
    }

    /**
     * 返回客户端数据
     */
    private void returnJson(HttpServletResponse response, String result) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(result);

        } catch (IOException e) {
        } finally {
            if (writer != null) {
                writer.close();
            }
        }

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
//        System.out.println("拦截器2 postHandle： ");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
//        System.out.println("拦截器3 afterCompletion： ");
    }
}
